import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { validateVenueData } from '../../utils/validators/venueValidator';

export class AdminVenueController extends BaseController {
  // 获取场馆列表
  async getVenues(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, pageSize = 20, keyword = '', status, city, country } = req.query;
      const skip = (Number(page) - 1) * Number(pageSize);

      // 构建查询条件
      const where: any = {};
      
      if (keyword) {
        where.OR = [
          { name: { contains: keyword as string } },
          { description: { contains: keyword as string } },
          { address: { contains: keyword as string } },
          { city: { contains: keyword as string } }
        ];
      }

      if (status) {
        where.status = status;
      }

      if (city) {
        where.city = city;
      }

      if (country) {
        where.country = country;
      }

      // 查询场馆列表
      const [venues, total] = await Promise.all([
        prisma.venue.findMany({
          where,
          skip,
          take: Number(pageSize),
          include: {
            _count: {
              select: {
                floors: true,
                performances: true
              }
            }
          },
          orderBy: {
            createdAt: 'desc'
          }
        }),
        prisma.venue.count({ where })
      ]);

      ResponseUtils.success(res, {
        data: venues,
        pagination: {
          total,
          page: Number(page),
          pageSize: Number(pageSize),
          totalPages: Math.ceil(total / Number(pageSize))
        }
      }, '获取场馆列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取场馆详情
  async getVenueById(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const venueId = parseInt(id);

      if (isNaN(venueId)) {
        ResponseUtils.badRequest(res, '无效的场馆ID');
        return;
      }

      const venue = await prisma.venue.findUnique({
        where: { id: venueId },
        include: {
          floors: {
            orderBy: { level: 'asc' }
          },
          performances: {
            take: 10,
            orderBy: { startTime: 'desc' },
            include: {
              artist: {
                select: {
                  id: true,
                  name: true,
                  avatar: true
                }
              }
            }
          },
          _count: {
            select: {
              floors: true,
              performances: true
            }
          }
        }
      });

      if (!venue) {
        ResponseUtils.notFound(res, '场馆不存在');
        return;
      }

      ResponseUtils.success(res, venue, '获取场馆详情成功');
    } catch (error) {
      next(error);
    }
  }

  // 创建场馆
  async createVenue(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const venueData = req.body;

      // 验证数据
      const validationResult = validateVenueData(venueData);
      if (!validationResult.isValid) {
        ResponseUtils.badRequest(res, validationResult.errors.join(', '));
        return;
      }

      // 检查场馆名称是否已存在
      const existingVenue = await prisma.venue.findUnique({
        where: { name: venueData.name }
      });

      if (existingVenue) {
        ResponseUtils.badRequest(res, '场馆名称已存在');
        return;
      }

      // 创建场馆
      const venue = await prisma.venue.create({
        data: {
          name: venueData.name,
          description: venueData.description,
          address: venueData.address,
          city: venueData.city,
          country: venueData.country,
          capacity: venueData.capacity ? parseInt(venueData.capacity) : null,
          contactPhone: venueData.contactPhone,
          contactEmail: venueData.contactEmail,
          website: venueData.website,
          latitude: venueData.latitude ? parseFloat(venueData.latitude) : null,
          longitude: venueData.longitude ? parseFloat(venueData.longitude) : null,
          status: venueData.status || 'ACTIVE'
        }
      });

      ResponseUtils.success(res, venue, '创建场馆成功');
    } catch (error) {
      next(error);
    }
  }

  // 更新场馆
  async updateVenue(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const venueId = parseInt(id);
      const updateData = req.body;

      if (isNaN(venueId)) {
        ResponseUtils.badRequest(res, '无效的场馆ID');
        return;
      }

      // 验证数据
      const validationResult = validateVenueData(updateData, true);
      if (!validationResult.isValid) {
        ResponseUtils.badRequest(res, validationResult.errors.join(', '));
        return;
      }

      // 检查场馆是否存在
      const existingVenue = await prisma.venue.findUnique({
        where: { id: venueId }
      });

      if (!existingVenue) {
        ResponseUtils.notFound(res, '场馆不存在');
        return;
      }

      // 如果更新名称，检查是否与其他场馆重复
      if (updateData.name && updateData.name !== existingVenue.name) {
        const duplicateVenue = await prisma.venue.findUnique({
          where: { name: updateData.name }
        });

        if (duplicateVenue) {
          ResponseUtils.badRequest(res, '场馆名称已存在');
          return;
        }
      }

      // 更新场馆
      const venue = await prisma.venue.update({
        where: { id: venueId },
        data: {
          name: updateData.name,
          description: updateData.description,
          address: updateData.address,
          city: updateData.city,
          country: updateData.country,
          capacity: updateData.capacity ? parseInt(updateData.capacity) : null,
          contactPhone: updateData.contactPhone,
          contactEmail: updateData.contactEmail,
          website: updateData.website,
          latitude: updateData.latitude ? parseFloat(updateData.latitude) : null,
          longitude: updateData.longitude ? parseFloat(updateData.longitude) : null,
          status: updateData.status
        }
      });

      ResponseUtils.success(res, venue, '更新场馆成功');
    } catch (error) {
      next(error);
    }
  }

  // 删除场馆
  async deleteVenue(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const venueId = parseInt(id);

      if (isNaN(venueId)) {
        ResponseUtils.badRequest(res, '无效的场馆ID');
        return;
      }

      // 检查场馆是否存在
      const existingVenue = await prisma.venue.findUnique({
        where: { id: venueId },
        include: {
          _count: {
            select: {
              floors: true,
              performances: true
            }
          }
        }
      });

      if (!existingVenue) {
        ResponseUtils.notFound(res, '场馆不存在');
        return;
      }

      // 检查是否有关联的楼层或演出
      if (existingVenue._count.floors > 0 || existingVenue._count.performances > 0) {
        ResponseUtils.badRequest(res, '场馆下存在楼层或演出，无法删除');
        return;
      }

      // 删除场馆
      await prisma.venue.delete({
        where: { id: venueId }
      });

      ResponseUtils.success(res, null, '删除场馆成功');
    } catch (error) {
      next(error);
    }
  }

  // 批量更新场馆状态
  async batchUpdateVenueStatus(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { ids, status } = req.body;

      if (!Array.isArray(ids) || ids.length === 0) {
        ResponseUtils.badRequest(res, '请选择要更新的场馆');
        return;
      }

      if (!status || !['ACTIVE', 'INACTIVE', 'MAINTENANCE'].includes(status)) {
        ResponseUtils.badRequest(res, '无效的状态值');
        return;
      }

      // 批量更新状态
      const result = await prisma.venue.updateMany({
        where: {
          id: {
            in: ids.map((id: any) => parseInt(id))
          }
        },
        data: {
          status: status as any
        }
      });

      ResponseUtils.success(res, { updatedCount: result.count }, '批量更新场馆状态成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取场馆统计信息
  async getVenueStats(_req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const [totalVenues, activeVenues, inactiveVenues, maintenanceVenues] = await Promise.all([
        prisma.venue.count(),
        prisma.venue.count({ where: { status: 'ACTIVE' } }),
        prisma.venue.count({ where: { status: 'INACTIVE' } }),
        prisma.venue.count({ where: { status: 'MAINTENANCE' } })
      ]);

      const cityStats = await prisma.venue.groupBy({
        by: ['city'],
        _count: {
          id: true
        },
        orderBy: {
          _count: {
            id: 'desc'
          }
        },
        take: 10
      });

      const countryStats = await prisma.venue.groupBy({
        by: ['country'],
        _count: {
          id: true
        },
        orderBy: {
          _count: {
            id: 'desc'
          }
        }
      });

      ResponseUtils.success(res, {
        total: totalVenues,
        active: activeVenues,
        inactive: inactiveVenues,
        maintenance: maintenanceVenues,
        cityStats: cityStats.map(item => ({
          city: item.city,
          count: item._count.id
        })),
        countryStats: countryStats.map(item => ({
          country: item.country,
          count: item._count.id
        }))
      }, '获取场馆统计信息成功');
    } catch (error) {
      next(error);
    }
  }

  // 根据场地ID获取楼层列表
  async getFloorsByVenue(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { venueId } = req.params;
      const venueIdNum = parseInt(venueId);

      if (isNaN(venueIdNum)) {
        ResponseUtils.badRequest(res, '无效的场地ID');
        return;
      }

      // 验证场地是否存在
      const venue = await prisma.venue.findUnique({
        where: { id: venueIdNum }
      });

      if (!venue) {
        ResponseUtils.notFound(res, '场地不存在');
        return;
      }

      // 获取该场地的所有楼层
      const floors = await prisma.floor.findMany({
        where: { 
          venueId: venueIdNum,
          status: 'ACTIVE' // 只获取活跃状态的楼层
        },
        select: {
          id: true,
          name: true,
          level: true,
          description: true,
          status: true,
          createdAt: true,
          updatedAt: true
        },
        orderBy: [
          { level: 'asc' }, // 按楼层级别排序
          { name: 'asc' }   // 同级别按名称排序
        ]
      });

      ResponseUtils.success(res, floors, '获取楼层列表成功');
    } catch (error) {
      next(error);
    }
  }
}
